import { Module, Global } from '@nestjs/common'
import { createLogger, format, transports } from 'winston'
import {
  utilities as nestWinstonModuleUtilities,
  WinstonModule,
} from 'nest-winston'
import 'winston-daily-rotate-file'

@Global()
@Module({
  providers: [
    {
      provide: 'WINSTON_LOGGER',
      useFactory: () => {
        const instance = createLogger({
          // 配置winston
          transports: [
            //控制台日志
            new transports.Console({
              level: 'info',
              format: format.combine(
                format.timestamp(),
                format.ms(),
                nestWinstonModuleUtilities.format.nestLike('MyApp', {
                  colors: true,
                  prettyPrint: true,
                  processId: true,
                  appName: true,
                }),
              ),
            }),
            //错误日志
            new transports.DailyRotateFile({
              level: 'error',
              dirname: 'logs',
              filename: 'application-error-%DATE%.log',
              datePattern: 'YYYY-MM-DD-HH',
              zippedArchive: true,
              maxSize: '20m',
              maxFiles: '14d',
            }),
            //警告日志
            new transports.DailyRotateFile({
              level: 'warn',
              dirname: 'logs',
              filename: 'application-warn-%DATE%.log',
              datePattern: 'YYYY-MM-DD-HH',
              zippedArchive: true,
              maxSize: '20m',
              maxFiles: '14d',
            }),
          ],
        })
        // 创建winston日志实例
        return WinstonModule.createLogger({
          instance,
        })
      },
    },
  ],
  exports: ['WINSTON_LOGGER'],
})
export class LogModule {}
